<template>
  <div>
    <h2>{{ this.id ? "修改音乐：" : "添加音乐：" }}</h2>
    <el-form label-width="100px" :model="models" ref="refForm" :rules="rules">
      <el-form-item label="音乐名称：" prop="title">
        <el-input v-model="models.title" style="width:480px"></el-input>
      </el-form-item>
      <el-form-item label="演唱者：" prop="artist">
        <el-input v-model="models.artist" style="width:480px"></el-input>
      </el-form-item>
      <el-form-item label="音乐链接：" prop="url">
        <el-input v-model="models.url" style="width:480px"></el-input>
      </el-form-item>
      <el-form-item label="音乐封面：" prop="pic">
        <el-input v-model="models.pic" style="width:480px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="musicAdd">{{
          this.id ? "修 改" : "确认"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getMusicadd, getMusicedit, getMusicdetail } from "@/api/index.js";
export default {
  props: ["id"],
  data() {
    return {
      models: {},
      rules: {
        title: [{ required: true, message: "请输入音乐名称", trigger: "blur" }],
        artist: [
          { required: true, message: "请输入音乐作者", trigger: "blur" },
        ],
        url: [{ required: true, message: "请输入音乐链接", trigger: "blur" }],
        pic: [{ required: true, message: "请输入封面链接", trigger: "blur" }],
      },
    };
  },
  mounted() {
    console.log(this.id);
    this.id && this.musicEdit();
  },
  methods: {
    musicAdd() {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          if (this.id) {
            getMusicedit(this.id, this.models).then((res) => {
              console.log(res);
              if (res.data.status == 200) {
                this.$message.success(res.data.msg);
                this.$router.push("/musicList");
              }
            });
          } else {
            getMusicadd(this.models).then((res) => {
              if (res.status == 200) {
                this.$message.success("添加成功！");
                this.$router.push("/musicList");
                this.$refs.refForm.resetFields();
              }
            });
          }
        } else {
          this.$message.error("请将数据补充完整！");
        }
      });
    },
    musicEdit() {
      getMusicdetail(this.id).then((res) => {
        this.models = res.data;
      });
    },
  },
};
</script>

<style lang="less" scoped></style>
